package com.onlyxiahui.extend.query.hibernate.syntax.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.onlyxiahui.extend.query.hibernate.QueryWrapper;

/**
 * 
 * Description <br>
 * Date 2020-02-01 11:32:53<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */
public class UpdateHqlUtil {

	public static String getUpdateHql(String entityName, List<String> keyNames, QueryWrapper qw) {
		StringBuilder hql = new StringBuilder();
		Map<String, Object> map = (null == qw) ? null : qw.getParameterMap();
		if (map != null && !map.isEmpty()) {
			String set = getSetHql(entityName, map, keyNames);
			String where = getWhereHql(keyNames);
			hql.append(set);
			hql.append(" ");
			hql.append(where);
		}
		return hql.toString();
	}

	public static String getUpdateHql(String entityName, String primaryKeyName, QueryWrapper qw) {
		StringBuilder hql = new StringBuilder();
		Map<String, Object> map = (null == qw) ? null : qw.getParameterMap();
		if (map != null && !map.isEmpty()) {
			List<String> keyNames = new ArrayList<>();
			keyNames.add(primaryKeyName);
			String set = getSetHql(entityName, map, keyNames);
			String where = getWhereHql(keyNames);
			hql.append(set);
			hql.append(" ");
			hql.append(where);
		}
		return hql.toString();
	}

	public static String getWhereHql(List<String> keyNames) {
		StringBuilder hql = new StringBuilder();
		if (keyNames != null && !keyNames.isEmpty()) {
			hql.append(" ");
			hql.append("where");
			hql.append(" ");
			int i = 0;
			for (String key : keyNames) {
				i++;
				if (i == 1) {
					hql.append(key);
					hql.append(" = ");
					hql.append(":");
					hql.append(key);
				} else {
					hql.append(" ");
					hql.append("and");
					hql.append(" ");
					hql.append(key);
					hql.append(" = ");
					hql.append(":");
					hql.append(key);
				}
			}
		}
		return hql.toString();
	}

	public static String getSetHql(String entityName, Map<String, Object> valueMap, List<String> outKeyNames) {
		StringBuilder hql = new StringBuilder();
		outKeyNames = (null == outKeyNames) ? new ArrayList<>() : outKeyNames;
		if (valueMap != null && !valueMap.isEmpty()) {
			Set<String> keySet = valueMap.keySet();
			hql.append("update ");
			hql.append(entityName);
			hql.append(" set ");
			int i = 0;
			// int size=keySet.size();
			for (String key : keySet) {
				if (!outKeyNames.contains(key)) {
					i++;
					if (i == 1) {
						hql.append(key);
						hql.append(" = ");
						hql.append(":");
						hql.append(key);
					} else {
						hql.append(",");
						hql.append(key);
						hql.append(" = ");
						hql.append(":");
						hql.append(key);
					}
				}
			}
		}
		return hql.toString();
	}
}
